package com.itheima.controller.backend.security.order;


import com.itheima.common.constant.RedisConstant;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.common.entity.Result;
import com.itheima.common.utils.AliOssUtil;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Autowired
    SetmealService setmealService;
    @Autowired
    AliOssUtil aliOssUtil;
    @Autowired
    RedisTemplate redisTemplate;

    @PostMapping("/add")
    public Result add(@RequestBody Setmeal setmeal, @RequestParam String checkgroupIds) {

        Integer[] checkGroupIds = new Integer[checkgroupIds.split(",").length];
        for (int i = 0; i < checkgroupIds.split(",").length; i++) {
            checkGroupIds[i] = Integer.parseInt(checkgroupIds.split(",")[i]);
        }


        setmealService.add(setmeal,checkGroupIds);
        return new Result(true,"添加成功");

    }

    @PostMapping("/edit")
    public Result edit(@RequestBody Setmeal setmeal, @RequestParam String checkGroupIds) {

        Integer[] checkGroupIdss = new Integer[checkGroupIds.split(",").length];
        for (int i = 0; i < checkGroupIds.split(",").length; i++) {
            checkGroupIdss[i] = Integer.parseInt(checkGroupIds.split(",")[i]);
        }
        setmealService.edit(setmeal,checkGroupIdss);
        return new Result(true,"编辑成功");
    }

    @GetMapping("/findById")
    public Result findById(@RequestParam Integer id) {
        Setmeal setmeal = setmealService.findById(id);
        return new Result(true,"查询成功",setmeal);
    }

    @PostMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {

        List<Setmeal> setmealList = setmealService.findPage(queryPageBean);
        Long total = setmealService.findCount()  ;
        return new PageResult(total, setmealList);
    }

    @PostMapping("/upload")
    public Result upload( @RequestParam("imgFile") MultipartFile imgFile) throws IOException {



            String originalFilename = imgFile.getOriginalFilename();
            // 获取文件后缀名
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String filename = UUID.randomUUID().toString()+ fileExtension;
            String URL = aliOssUtil.upload(imgFile.getBytes(), filename);

//            将每次上传到阿里云的图片URL保存在Redis的set集合中
            redisTemplate.opsForSet().add(RedisConstant.SETMEAL_PIC_RESOURCES,URL);


            return new Result(true , "上传成功" ,URL);

    }

}
